#include "APP_Mqtt.h"

static MQTTClient client;
static MQTTClient_connectOptions options=MQTTClient_connectOptions_initializer;
static MQTTClient_message msg = MQTTClient_message_initializer;

//自定义回调函数 处理接收数据
static int (*Recv_Cb)(char* payload,int payloadLen);

//客户端断开连接时调用回调函数
void Lost_Cb(void* context, char* cause)
{
    log_error("客户端断开连接原因: %s\n",cause);
}
//客户端接收到订阅数据时回调函数
int Arrived_Cb(void* context, char* topicName, int topicLen, MQTTClient_message* message)
{
    int status = 1;
    log_info("客户端数据接收回调函数触发");
    // log_info("接收数据为:\n%s",message->payload);
    // log_info("数据长度为: %d",message->payloadlen);
    int ret = Recv_Cb(message->payload,message->payloadlen);
    if(ret != 0)
    {
        status = 0;
        perror("消息处理失败 ");
    }
    //释放消息相关的资源
    MQTTClient_freeMessage(&message);//释放消息结构体
    MQTTClient_free(topicName);//释放主题字符串
    return status;//成功返回1 失败返回0

}
//客户端发送数据成功时回调函数
void delivery_Cb(void* context, MQTTClient_deliveryToken dt)
{
    log_info("数据发送成功\n");
}

//初始化mqtt客M户端  成功返回 0 失败返回 -1
int APP_MQTT_Init(void)
{
    //初始化mqtt客户端
    int ret = MQTTClient_create(&client,MQTT_SERVER_URL,CLIENT_ID,MQTTCLIENT_PERSISTENCE_NONE,NULL);
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("mqtt客户端创建失败 ");
        return -1;
    }
    //设置回调函数 断开回调函数   接收回调函数  发送成功回调函数 //注意***
    ret = MQTTClient_setCallbacks(client,NULL,Lost_Cb,Arrived_Cb,delivery_Cb);
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("mqtt回调函数设置失败 ");
        MQTTClient_destroy(&client);//释放mqtt客户端资源
        return -1;
    }
    //连接mqtt服务器
    ret = MQTTClient_connect(client,&options); //z注意***
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("mqtt服务器连接失败 ");
        MQTTClient_destroy(&client);//释放mqtt客户端资源
        return -1;
    }
    //订阅信息主题
    MQTTClient_subscribe(client,MQTT_RECV_TOPIC,MQTT_QOS);
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("mqtt主题订阅失败 ");
        MQTTClient_disconnect(client,0);//断开连接     
        MQTTClient_destroy(&client);//释放mqtt客户端资源
        return -1;
    }
    return 0;
}

//注册mqtt客户端相关回调函数 接收数据的回调函数
void APP_MQTT_Register_Callback(int (*Cb)(char* data,int len))
{
    Recv_Cb = Cb;//将传入进来的函数指针赋值给Recv_Cb
}

//发送mqtt消息 Payload:具体发送数据  PayloadLen:数据长度  
//发送成功: 0 发送失败: -1
int APP_MQTT_Send(char* Payload,int PayloadLen)
{
    //配置消息结构体
    msg.payload = Payload;
    msg.payloadlen = PayloadLen;
    msg.qos = MQTT_QOS;
    int ret = MQTTClient_publishMessage(client,MQTT_SEND_TOPIC,&msg,NULL);
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("消息发送失败 ");

        return -1;
    }
    return 0;
}

//释放mqtt客户端相关资源
void APP_MQTT_Close(void)
{
    MQTTClient_disconnect(client,0);//断开连接     
    MQTTClient_destroy(&client);//释放mqtt客户端资源  
}
